<?php

	namespace Phptricks\system\library\bootstrap;

	/**
	 *  phptricks Framework 
	 *  link http://phptricks.net/Framework
	 *  date start 2014
	 */
	use Phptricks\system\library\PhptricksExceptions\PhptricksExceptions as Exc;
	use Phptricks\system\library\loaders\loader as loaders;
	use Phptricks\system\library\uri\uri as URI;
	use Phptricks\system\library\hooks\hooks as hooks;
	use Phptricks\system\library\basecontroller\basecontroller as basecontroller;
	use Phptricks\app\controllers\base\base as base;

	final class bootstrap{

		private $_bootstrap_class_name = null;
		private $_bootstrap_function_name = null;
		private $_bootstrap_function_param = null;
		private $_bootstrap_default_controller;
		private $_basecontroller = null;
		private $_controller = null;
		private $_uri = null;
		private $_loader = null;
		private $_hooks = null;
		public static $_error_controller = null;

		public function __construct(){
			$this->_bootstrap_default_controller = 'Phptricks\app\controllers\error\error';
			$this->_loader = loaders::getinstance();
			$this->_uri = URI::getinstance();
			// start hooks
			$this->_hooks = hooks::getinstance();
			$this->_hooks->_initialize($this->_uri->_array_return, true);
			$this->_hooks->_run('before');
			$this->_uri->_array_return = $this->_hooks->_uri;

			$this->_basecontroller = basecontroller::getinstance();
			$this->_geturi();
			$this->_LoadDefaultControler();
			$this->_callControllerMethod();
		}

		private function _geturi(){
			$this->_bootstrap_class_name = 'Phptricks\app\controllers\\' . $this->_uri->_array_return['class'] . '\\' . $this->_uri->_array_return['class'];
			$this->_bootstrap_function_name = $this->_uri->_array_return['function'];
			$this->_bootstrap_function_param = $this->_uri->_array_return['args'];
		}

		private function _LoadDefaultControler(){
			$get_class_name = $this->_bootstrap_class_name;
			if (class_exists($get_class_name) == false) {
				$this->_error_LoadDefaultControler(404);
			}
			$this->_controller = new $get_class_name();
			return true;
		}

		private function _callControllerMethod(){
			if ($this->_check_method() !== true) {
				$this->_error_LoadDefaultControler(404);
			}
			if (count($this->_bootstrap_function_param) > 0) {
				call_user_func_array(array($this->_controller, $this->_bootstrap_function_name), $this->_bootstrap_function_param);
			} else {
				$this->_controller->{$this->_bootstrap_function_name}(array());
			}
			return true;
		}

		private function _error_LoadDefaultControler($error_type = '404'){
			$this->_controller = base::getinstance();
			$this->_controller->_errors('404', $this->_uri->_array_return['fulluri']);
			die();
		}

		private function _check_method(){
			$class_methods = get_class_methods($this->_controller);
			if (in_array($this->_bootstrap_function_name, $class_methods)) {
				return true;
			} else {
				$this->_controller->_errors('404', $this->_uri->_array_return['fulluri']);
			}
		}

	}
	